import Toast from "../../miniprogram_npm/@vant/weapp/toast/toast";
const app = getApp()
import {
  ajaxGetOrderList,
  ajaxQueryOrderState
} from '../../api/order'

let isLoading = false;

Page({

  /**
   * 页面的初始数据
   */
  data: {
    //自定义导航高度
    customNavHeight: app.globalData.customNavInfo.navHeight,
    baseURL: app.globalData.config.baseURL,
    // tab active
    active: 0,
    list: [],
    userInfo: null,
    // 分页
    pagingOptions: {
      //分页页码
      pageNo: 1,
      //分页每页条数
      pageSize: 10,
      //下拉状态控制
      refreshState: 0,
      //上拉状态控制
      pushState: 0,
    },
    // 前往浏览详情的订单id
    detailsOrderId: null,
    // 支付成功订单id
    paySuccessOrderId: null,
    // 支付取消订单id
    cancelOrderId: null
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    //监听
    app.addWatchHandle({
      id: 'orderingPage',
      callBack: (e) => {
        this.updateUserInfo();
      }
    })
  },
  // tab change
  tabChange(e) {
    this.setData({
      active: e.detail.index || 0
    })
    this.refresh(true);
  },
  //获取数据列表
  getList() {
    return new Promise((resolve, reject) => {
      let {
        pageNo,
        pageSize
      } = this.data.pagingOptions;
      ajaxGetOrderList({
        pageNo,
        pageSize,
        // orderStatus 未分配1 已分配2
        orderStatus: this.data.active == 0 ? 1 : 2
      }).then((resp) => {
        let list = (resp.data || []).map(item => {
          item.productInfoList = item.productInfoList || [];
          return item;
        })
        resolve(list);
      }).catch((err) => {
        Toast(err.msg || '错误')
        resolve([]);
      })
    })
  },
  //下拉刷新
  refresh(showLoading) {
    // 没有登录不查询订单
    if (!this.data.userInfo) {
      this.setData({
        'pagingOptions.refreshState': 1
      })
      return;
    }
    if (isLoading) {
      return;
    }
    isLoading = true;
    if (showLoading) {
      //loading
      Toast.loading({
        message: '正在加载',
        forbidClick: true,
        duration: 0
      });
    }
    this.setData({
      'pagingOptions.pageNo': 1
    }, () => {
      //请求数据第一页数据
      this.getList().then((list) => {
        this.setData({
          list: list.length ? list : []
        }, async () => {
          this.setData({
            'pagingOptions.refreshState': 1,
            'pagingOptions.pushState': list.length >= this.data.pagingOptions.pageSize ? 2 : 3
          })
          await app.myNextTick()
          Toast.clear();
          isLoading = false;
          // 有支付成功或取消id 前往订单详情页面
          if (this.paySuccessOrderId || this.cancelOrderId) {
            this.setData({
              detailsOrderId: this.paySuccessOrderId || this.cancelOrderId
            }, () => {
              if (this.cancelOrderId) {
                this.cancelOrderId = null;
                app.commonNavigateTo('/pages/ordering/orderPayment/index', {
                  orderId: this.data.detailsOrderId
                })
              } else {
                this.paySuccessOrderId = null;
                app.commonNavigateTo(`/pages/order/orderDetails/index?orderId=${this.data.detailsOrderId}`)
              }
            })
          }
        })
      }).catch(async (err) => {
        this.setData({
          'pagingOptions.refreshState': 1
        })
        isLoading = false;
        await app.myNextTick()
        Toast.clear();
        Toast('加载失败');
      })
    })
  },
  //上拉刷新
  toload(e) {
    // 没有登录不查询订单
    if (!this.data.userInfo) {
      return;
    }
    this.setData({
      'pagingOptions.pageNo': this.data.pagingOptions.pageNo + 1
    }, () => {
      //请求数据第一页数据
      this.getList().then((list) => {
        this.data.list.push(...(list ? list : []));
        this.setData({
          list: this.data.list,
          'pagingOptions.pushState': list.length >= this.data.pagingOptions.pageSize ? 2 : 3
        })
      }).catch((err) => {
        this.setData({
          'pagingOptions.pushState': 2
        })
      })
    })
  },
  // 订单详情
  goOrderDetails(e) {
    let {
      index
    } = e.currentTarget.dataset,
      item = this.data.list[index],
      orderId = item.orderId;
    this.setData({
      detailsOrderId: orderId
    }, () => {
      //待支付
      if (item.orderStatus == 0) {
        app.commonNavigateTo('/pages/ordering/orderPayment/index', {
          orderId
        })
      } else {
        //已完成
        app.commonNavigateTo(`/pages/order/orderDetails/index?orderId=${orderId}`)
      }
    })
  },
  //查询订单状态
  queryOrderState(orderId) {
    this.setData({
      detailsOrderId: null
    }, async () => {
      try {
        let {
          data
        } = await ajaxQueryOrderState({
          orderId
        });
        data = data || {};
        let index = this.data.list.findIndex(item => {
          return item.orderId == orderId;
        });
        if (index != -1) {
          // 待核销分类，订单状态 不是0未支付、1待核销都删除、4售后处理中，应该在历史单里
          if (this.data.active == 0 && [0, 1, 4].indexOf(data.orderStatus) == -1) {
            this.data.list.splice(index, 1)
            this.setData({
              list: this.data.list
            })
          } else {
            // 修改订单状态
            this.setData({
              [`list[${index}].orderStatus`]: data.orderStatus,
              [`list[${index}].applyRefundTime`]: data.applyRefundTime,
              [`list[${index}].closeTime`]: data.closeTime,
              [`list[${index}].createTime`]: data.createTime
            })
          }
        }
      } catch (err) {
        Toast(err.msg || '错误');
      }
    })
  },
  // 更新用户信息
  updateUserInfo(isRefresh = true) {
    let isChangeUser = JSON.stringify(this.data.userInfo || {}) != JSON.stringify(app.globalData.userInfo || {});
    if (isChangeUser) {
      this.setData({
        userInfo: JSON.parse(JSON.stringify(app.globalData.userInfo))
      })
    }
    if (!isRefresh) {
      return;
    }
    if (isChangeUser || !this.data.list.length) {
      // 更新页面数据
      this.refresh(true);
    }
  },
  // 去注册登录
  toLogin() {
    app.commonNavigateTo('/pages/registerLogin/home/index')
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    //有支付或待支付订单id
    let {
      orderId,
      cancelOrderId,
      triggerRefresh
    } = app.storeModules.order.data;
    if (orderId || cancelOrderId || triggerRefresh) {
      //清空id 转存
      if (orderId) {
        this.paySuccessOrderId = orderId;
        app.storeModules.order.data.orderId = null;
      } else if (cancelOrderId) {
        this.cancelOrderId = cancelOrderId;
        app.storeModules.order.data.cancelOrderId = null;
      }
      //更新用户信息
      this.updateUserInfo(false);
      this.setData({
        active: 0
      })
      this.refresh(true);
    } else if (this.data.detailsOrderId) {
      //查询浏览详情的订单状态
      this.queryOrderState(this.data.detailsOrderId);
    } else {
      //更新页面数据
      this.updateUserInfo();
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  }
})